import sys
from PySide6.QtWidgets import (QApplication, QWidget, QTableWidget, 
                             QTableWidgetItem, QHBoxLayout, QVBoxLayout)
from PySide6.QtCore import Qt, QMimeData, QPoint
from PySide6.QtGui import QDrag, QFont, QColor

class DraggableTableWidget(QTableWidget):
    """支持拖放的表格控件"""
    def __init__(self, rows, cols, title, parent=None):
        super().__init__(rows, cols, parent)
        self.setHorizontalHeaderLabels([f"列 {i+1}" for i in range(cols)])
        self.setDragEnabled(True)       # 启用拖动
        self.setAcceptDrops(True)       # 接受拖放
        self.setSelectionMode(QTableWidget.ExtendedSelection)  # 支持多选
        self.setDragDropMode(QTableWidget.DragDrop)
        self.setDefaultDropAction(Qt.CopyAction)  # 默认移动操作
        
        # 填充示例数据
        for row in range(rows):
            for col in range(cols):
                item = QTableWidgetItem(f"{title} ({row+1},{col+1})")
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(row, col, item)
    
    def startDrag(self, supported_actions):
        """开始拖动时调用"""
        # 获取选中的单元格
        selected_items = self.selectedItems()
        if not selected_items:
            return super().startDrag(supported_actions)
        
        # 准备拖放数据
        mime_data = QMimeData()
        
        # 存储数据格式：行,列,内容;行,列,内容...
        data = []
        for item in selected_items:
            data.append(f"{item.row()},{item.column()},{item.text()}")
        mime_data.setText(";".join(data))
        item=self.item(2,2)
        item.setBackground(QColor("#4096ff"))
        # 创建拖动对象
        drag = QDrag(self)
        drag.setMimeData(mime_data)
        
        # 执行拖动
        result = drag.exec_(supported_actions)
        if result == Qt.MoveAction:
            # 如果是移动操作，删除原单元格内容
            for item in selected_items:
                self.takeItem(item.row(), item.column())
    
    def dragEnterEvent(self, event):
        """拖入事件"""
        if event.mimeData().hasText():
            # 只接受来自其他表格的拖放
            if event.source() != self:
                event.acceptProposedAction()
        else:
            super().dragEnterEvent(event)
    
    def dragMoveEvent(self, event):
        """拖动移动事件"""
        if event.mimeData().hasText() and event.source() != self:
            event.acceptProposedAction()
        else:
            event.acceptProposedAction()
            # super().dragMoveEvent(event)
    
    def dropEvent(self, event):
        """拖放完成事件"""
        if event.mimeData().hasText() and event.source() != self:
            # 获取拖放位置
            pos = event.pos()
            index = self.indexAt(pos)
            
            # 如果拖放到无效位置，默认放到最后一行
            if not index.isValid():
                row = self.rowCount()
                col = 0
                self.insertRow(row)
            else:
                row = index.row()
                col = index.column()
            
            # 解析拖放的数据
            data = event.mimeData().text().split(';')
            
            # 插入数据到目标表格
            current_row = row
            for item_data in data:
                r, c, text = item_data.split(',', 2)
                
                # 如果当前行已满，插入新行
                if col >= self.columnCount():
                    current_row += 1
                    col = 0
                    if current_row >= self.rowCount():
                        self.insertRow(current_row)
                
                # 创建新单元格
                new_item = QTableWidgetItem(text)
                new_item.setTextAlignment(Qt.AlignCenter)
                self.setItem(current_row, col, new_item)
                
                col += 1
            
            event.acceptProposedAction()
        else:
            super().dropEvent(event)

class TableDragDropDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle("两个表格间拖放示例")
        self.setGeometry(100, 100, 1000, 600)
        
        # 创建主布局
        main_layout = QHBoxLayout()
        
        # 创建两个可拖放的表格
        self.table1 = DraggableTableWidget(5, 3, "表格1")
        self.table2 = DraggableTableWidget(5, 3, "表格2")
        
        # 添加到主布局
        main_layout.addWidget(self.table1)
        main_layout.addWidget(self.table2)
        
        self.setLayout(main_layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TableDragDropDemo()
    window.show()
    sys.exit(app.exec())
